package com.wmyg.antifake.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program 前后端分离版妙码后台
 * @description 资源服务器配置
 * @author 王卓逸
 * @create 2019-04-15
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 自动注入token存储对象
     */
    @Autowired
    TokenStore memoryTokenStore;

    /**
     * 资源服务器安全配置
     * @param http 请求安全配置类
     * @throws Exception 可忽略
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/sign/**", "/notice/**", "/picture/**", "/record/downloadFile",
                        "/v2/api-docs", "/swagger-resources/configuration/ui",
                        "/swagger-resources","/swagger-resources/configuration/security",
                        "/swagger-ui.html","/course/coursebase/**",
                        "/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico").permitAll()
                .antMatchers("/**").authenticated()
                .anyRequest().authenticated()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {

                    /**
                     * 注销时删除token
                     */
                    @Override
                    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        String accessToken = httpServletRequest.getHeader("Authorization").substring(7);
                        if (null != accessToken || !("".equals(accessToken))) {
                            OAuth2AccessToken oAuth2AccessToken= memoryTokenStore.readAccessToken(accessToken);
                            if (null != oAuth2AccessToken) {
                                memoryTokenStore.removeAccessToken(oAuth2AccessToken);
                            }
                        }
                    }

                }).permitAll();
    }


}
